<template>
  <div>
    <div class="login_box">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="电影名称" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="导演" prop="director">
          <el-input v-model="form.director"></el-input>
        </el-form-item>
        <el-form-item label="主演" prop="protagonist">
          <el-input v-model="form.protagonist"></el-input>
        </el-form-item>
        <el-form-item label="故事简介" prop="synopsis">
          <el-input v-model="form.synopsis" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="电影链接" prop="link">
          <el-input v-model="form.link"></el-input>
        </el-form-item>
        <el-form-item label="电影封面" prop="img">
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="form.img" :src="form.img" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addMovie">添加</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
var COS = require('cos-js-sdk-v5');

// SECRETID 和 SECRETKEY请登录 https://console.cloud.tencent.com/cam/capi 进行查看和管理
var cos = new COS({
  SecretId: 'AKID73koc9QQ9bmgJfjX4JHzQaS4PTGm21jA',
  SecretKey: 'C7l8F5evvf8KFuIrDJ9hyyiETQ7XfW7Q',
});
export default {
  data() {
    return {
      uploadKey: '',
      imageUrl: '',
      form: {
        name: '', // 电影名称
        director: '', // 导演
        protagonist: '', // 主演
        synopsis: '', // 故事简介
        img: '', // 封面
        link:'' // 视频链接
      },
      infoArr: JSON.parse(localStorage.getItem('infoArr')) || [],
      rules: {
        name: [{ required: true, message: '请填写电影名称', trigger: 'blur' }],
        director: [{ required: true, message: '请填写导演', trigger: 'blur' }],
        protagonist: [
          { required: true, message: '请填写主演', trigger: 'blur' },
        ],
        synopsis: [
          { required: true, message: '请填写故事简介', trigger: 'blur' },
        ],
        img: [{ required: true, message: '未上传电影封面', trigger: 'blur' }],
        link: [{ required: true, message: '未提供链接', trigger: 'blur' }],
      },
    };
  },
  methods: {
    addMovie() {
      this.$refs.form.validate().then(res => {
        if (res) {
          // 创建id，修改和删除时要用到
          this.form.id = Date.now().toString();
          this.infoArr.push(this.form);
          localStorage.setItem('infoArr', JSON.stringify(this.infoArr));
          this.$message.success('添加成功');
          this.form = {};
          this.$router.push('/manage');
        } else {
          this.$message.warning('添加失败，检查填写项');
        }
      });
    },
    getURL(uploadKey) {
      // 上传成功后，访问对象获取图片链接，用来回显
      return cos.getObjectUrl(
        {
          Bucket: 'movie-1312551928' /* 填入您自己的存储桶，必须字段 */,
          Region: 'ap-guangzhou' /* 存储桶所在地域，例如ap-beijing，必须字段 */,
          Key: uploadKey /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */,
          Sign: false /* 获取带签名的对象URL */,
        },
        (err, data) => {
          if (err) return console.log(err);
          /* url为对象访问url */
          var url = data.Url;
          var previewURL =
            url +
            (url.indexOf('?') > -1 ? '&' : '?') +
            'response-content-disposition=inline'; // 补充预览的参数
          return previewURL;
        }
      );
    },
    handleAvatarSuccess(res, file) {
      console.log(123);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }

      const uploadKey = Date.now().toString();

      cos.uploadFile(
        {
          Bucket: 'movie-1312551928' /* 填写自己的bucket，必须字段 */,
          Region: 'ap-guangzhou' /* 存储桶所在地域，必须字段 */,
          Key: uploadKey /* 存储在桶里的对象键（例如:1.jpg，a/b/test.txt，图片.jpg）支持中文，必须字段 */,
          Body: file, // 上传文件对象
        },
        (err, data) => {
          if (err) {
            console.log('上传失败', err);
            this.$message.error('上传失败');
          } else {
            // console.log('上传成功');
            this.$message.success('上传成功');
            const url = this.getURL(uploadKey);
            this.imageUrl = url;
            this.form.img = url;
          }
        }
      );
    },
  },
};
</script>

<style scoped>
.avatar-uploader .el-upload {
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader-icon[data-v-106c86ed] {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
